#!/usr/bin/perl
##
# @param $1 install home
# @param $2 delimiter
# @param $3 host
# @param $4 port
# @param $5 username
# @param $6 password
#
use strict;
my ($MYSQL_HOME,$DELIM,$HOST,$PORT,$USER,$PASS) = @ARGV;
my $PARAM="";
$PARAM="$PARAM -h\"$HOST\"" if (defined($HOST) && $HOST ne "");
$PARAM="$PARAM -P\"$PORT\"" if (defined($PORT) && $PORT ne "");
$PARAM="$PARAM -u\"$USER\"" if (defined($USER) && $USER ne "");
$PARAM="$PARAM -p\"$PASS\"" if (defined($PASS) && $PASS ne "");
my $MYSQL="$MYSQL_HOME/bin/mysql";
my $MYSQLADMIN="$MYSQL_HOME/bin/mysqladmin";
if ($^O =~ m/MSWin32/) {
  $MYSQL =~ s/\//\\/g;
  $MYSQLADMIN =~ s/\//\\/g;
}
# Check if mysqld is alive
my $retmsg=`$MYSQLADMIN $PARAM ping 2>&1`;
chomp($retmsg);
if ( "$retmsg" ne "mysqld is alive" ) {
    print "em_result=Status${DELIM}Down\n";
    exit 0;
}
#print "em_result=Status${DELIM}Up\n";

#get error log file name
my $SQL="show status like 'slave_running'";
my $ret=`$MYSQL -s --skip-column-names $PARAM -e"$SQL"`;
chomp($ret);
my ($key , $slaverun) = split /[ \t]/,$ret;
my $is_slave;
if ( $slaverun =~ /ON/ )
{
  $is_slave=1;
}
else
{
  $is_slave=0;
}

#print "is_slave = $is_slave\n";

#set default value to avoid null value for dynamic properties
my $masterhost = '0.0.0.0';
my $masterport = 0;

$ret=`$MYSQL -s --skip-column-names $PARAM -e "show variables like 'datadir'"`;
chomp($ret);

my ( $key1, $datadir ) = split /[ \t]/, $ret;

chomp($datadir);

my $masterinfo=$datadir."master.info";
#print "masterinfo = $masterinfo\n";

if ( -f $masterinfo )
{
  if ( ! $is_slave )
  {
    #get modified time of master.info
    my $mtime = (stat ($masterinfo))[9];
    my $seconds_not_modified = time() - $mtime;
    #print "seconds_not_modified = $seconds_not_modified\n";

    # I think it is a slave if master.info was modified within 24 hours.
    if ( $seconds_not_modified <= 3600 * 24 )
    {
      $is_slave=1;
    }
  }
  open(my $fh, "<" , $masterinfo) or die "$0: can't open $masterinfo: $!";
  my @minfo = <$fh>;
  close($fh);
  chomp(@minfo);
  $masterhost=$minfo[3];
  $masterport=$minfo[6];
  if ( ! $masterhost or ! $masterport )
  {
    print "em_error=Content of ${masterinfo} is wrong\n";
    $masterhost = '0.0.0.0';
    $masterport = 0;
  }
}
elsif ($is_slave)
{
  print "em_error=There is no ${masterinfo} but slave thread is running\n";
}

my $is_master = 0;
my @list=`$MYSQL --skip-column-names -t $PARAM -e"show processlist"`;
chomp(@list);
for my $line (@list) {
next if ( $line =~ /^\+----/ );
  if ( $line =~ /Binlog Dump/i)
  {
    my @values = split(/ *\| */, $line);
    if ( $values[5] =~ /Binlog Dump/)
    {
      $is_master=1;
      last;
    }
  }
}

#mysqlrole: 0 none of slave and master
#mysqlrole: 1 only slave
#mysqlrole: 2 only master
#mysqlrole: 3 both slave and master
my $mysqlrole = $is_slave + $is_master * 2;

print "em_result=$mysqlrole|$masterhost|$masterport\n";

exit 0
